package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import entity.Cliente;

public class ClienteDAO implements AbstractDAO<Cliente>{

	private Connection conexao;

	public ClienteDAO() {
		conexao = ConnectionFactory.getConnection();
	}

	@Override
	public void insert(Cliente cliente) {

		try {
			OracleCallableStatement cstmt = (OracleCallableStatement) conexao
					.prepareCall("{call proc_insere_cliente(?,?,?,?)}");
			cstmt.setString(1, cliente.getNome());
			cstmt.setString(2, cliente.getTelefone());
			cstmt.setString(3, cliente.getCelular());
			cstmt.setString(4, cliente.getEmail());
			cstmt.execute();
			System.out.println("Inserido com sucesso");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(Cliente cliente) {

		try {
			OracleCallableStatement cstmt = (OracleCallableStatement) conexao
					.prepareCall("{call proc_altera_cliente(?,?,?,?,?)}");
			cstmt.setLong(1, cliente.getId());
			cstmt.setString(2, cliente.getNome());
			cstmt.setString(3, cliente.getTelefone());
			cstmt.setString(4, cliente.getCelular());
			cstmt.setString(5, cliente.getEmail());
			cstmt.execute();
			System.out.println("Alterado com sucesso");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delete(Cliente cliente) {
		
		try {
			OracleCallableStatement cstmt = (OracleCallableStatement) conexao
					.prepareCall("{call proc_deleta_cliente(?)}");
			cstmt.setLong(1, cliente.getId());
			cstmt.execute();
			System.out.println("Excluido com sucesso");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<Cliente> selectAll() {

		ArrayList<Cliente> clientes = new ArrayList<Cliente>();

		OracleCallableStatement cstmt;

		try {
			cstmt = (OracleCallableStatement) conexao
					.prepareCall("{call proc_get_cliente(?)}");
			cstmt.registerOutParameter("rs", OracleTypes.CURSOR);
			cstmt.execute();

			ResultSet rset = (ResultSet) cstmt.getObject("rs");
			
			while (rset.next()) {
				Cliente cliente = new Cliente();
				
				cliente.setId((long)rset.getInt("id_cliente"));
				System.out.println(rset.getInt("id_cliente"));
				cliente.setNome(rset.getString("nome"));
				cliente.setTelefone(rset.getString("telefone"));
				cliente.setCelular(rset.getString("celular"));
				cliente.setEmail(rset.getString("email"));
				
				clientes.add(cliente);
			}
			cstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return clientes;
	}
}

